import json

from flask import render_template, request, make_response, jsonify, redirect, url_for, session, current_app
from flask_wtf.csrf import generate_csrf
from sqlalchemy import and_
from information import db
from information.utils.models import User, Category, News
from information.utils.image_storage import storage
from information.utils.locks import  get_md5
from information.utils.response_code import RET
from information.utils import constants
from . import admin_blu
import time
from datetime import datetime, timedelta


'''后台登录'''
@admin_blu.route('/', methods=['GET','POST'])
def login():
    if request.method == 'POST':
        #接收前端的请求参数
        username = request.form.get('username')
        print(username)
        password = get_md5(request.form.get('password'))
        print(password)
        if not all([username,password]):
            return render_template('admin/login.html', errmsg='用户名或密码未输入')
        #查询数据库是否存在该用户
        user = User.query.filter(User.nick_name == username, User.password_hash == password).first()
        #print(user)
        if  user != None and user.is_admin == 1:
            response =redirect(url_for('admin.index'))
            session['username']=username
            return response
        return render_template('admin/index.html', errmsg = '用户名或密码错误')
    response = make_response('manage')
    #response.delete_cookie('username')
    #csrf_token = generate_csrf()
    return render_template('admin/login.html')

'''注销'''
@admin_blu.route('/logout', methods=['GET','POST'])
def logout():
    session.clear()
    # csrf_token = generate_csrf()
    return redirect(url_for('admin.login'))

'''进入后台'''
@admin_blu.route('/manage')
def index():
    # 从session中取到用户名
    username = session.get('username')
    print(username)
    # 如果没有取到，代表没有登录
    if not username:
        return redirect(url_for('admin.login'))
    user = User.query.filter(User.nick_name == username).first()
    return render_template('admin/index.html',user = user)

@admin_blu.route('/userCount/')
def user_count():
    # 获取当前时间
    now = time.localtime()
    # 获取当天的起始时间，默认00：00：00
    day_begin_str = '%d-%02d-%02d' % (now.tm_year, now.tm_mon, now.tm_mday)
    # 将str类型的起始时间转化为datetime
    day_begin_date = datetime.strptime(day_begin_str, '%Y-%m-%d')

    def get_total_count():
        # 统计不为管理员的用户数量
        total_count = User.query.filter(User.is_admin == False).count()
        return total_count

    def get_mon_count():
        # 获取当月的起始时间，默认00：00：00
        mon_begin_str = '%d-%02d-01' % (now.tm_year, now.tm_mon)
        # 将str类型的起始时间转化为datetime
        mon_begin_date = datetime.strptime(mon_begin_str, '%Y-%m-%d')
        # 月新增用户查询，排查管理员
        mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_begin_date).count()
        return mon_count

    def get_day_count():
        # 日新增用户查询，排查管理员
        day_count = User.query.filter(User.is_admin == False, User.create_time >= day_begin_date).count()
        return day_count

    def get_day_active_count():
        # 前一天的结束时间
        begin_date = day_begin_date + timedelta(days=-1, hours=19, minutes=15)
        # 当天的第一次显示数据的时间
        second_date = day_begin_date + timedelta(hours=8, minutes=15)
        # 当天的结束时间
        end_date = day_begin_date + timedelta(hours=19, minutes=15)
        # 存贮不同时间段的用户活跃量
        day_active_count = []
        # 统计前一天19：15之后到后一天8：15的用户活跃量
        count = User.query.filter(User.is_admin == False, User.last_login > begin_date, User.last_login <= second_date).count()
        day_active_count.append(count)
        # 统计当前8：15到19：15间的用户活跃量
        for x in range(0, 11):
            # 每一时间段统计的起始时间
            now_begin = second_date + timedelta(hours=x)
            # 每一时间段统计的结束时间
            now_end = now_begin + timedelta(hours=x + 1)
            # 统计每一时间段的用户活跃量
            count = User.query.filter(User.is_admin == False, User.last_login > now_begin,
                                      User.last_login <= now_end).count()
            # 将统计的用户活跃量结果写入存贮数组
            day_active_count.append(count)

        return day_active_count

    # 将统计用户所有的数据封装进字典
    data = {
        'total_count': get_total_count(),
        'mon_count': get_mon_count(),
        'day_count': get_day_count(),
        'active_count': get_day_active_count()
    }
    return render_template('admin/user_count.html',data = data)

@admin_blu.route('/user_list/')
def user_list():
    #接收前端传的当前页数
    current_page = int(request.args.get('page',1))
    #统计所有的用户数量，排除管理员
    total_count = User.query.filter(User.is_admin == False).count()
    #计算总页数
    total_page = total_count // constants.USER_FOLLOWED_MAX_COUNT
    #按照注册时间排序，并将分页之后的用户数据存入paginate
    paginates =  User.query.filter(User.is_admin == False).order_by(User.create_time.desc()).paginate(current_page, constants.USER_FOLLOWED_MAX_COUNT)
    #获取当前页的用户数据
    users = paginates.items
    #将前端所需要的所有数据封装进字典
    data ={
        'users': users,
        'current_page': current_page,
        'total_page': total_page
    }
    return render_template('admin/user_list.html',data = data)


@admin_blu.route('/news_review/')
def news_review():
    #获取前端的搜索关键字
    keywords = request.args.get('keywords')
    #接收前端传来的页数，默认1
    current_page = int(request.args.get('p', 1))
    #查询新闻的总数
    total_count = News.query.count()
    #计算新闻的总页数
    total_page = total_count //  constants.ADMIN_NEWS_PAGE_MAX_COUNT
    if keywords != None:
        # 按照注册时间排序，并将关键字匹配分页之后的用户数据存入paginate
        paginates = News.query.filter(News.title.like('%' + keywords + '%')).order_by(News.create_time.desc()).paginate(current_page, constants.ADMIN_NEWS_PAGE_MAX_COUNT)
    else:
        #按照注册时间排序，并将分页之后的用户数据存入paginate
        paginates = News.query.order_by(News.create_time.desc()).paginate(current_page, constants.ADMIN_NEWS_PAGE_MAX_COUNT)
    #查询当前页的新闻数据
    news_list = paginates.items

    data = {
        'news_list': news_list,
        'current_page': current_page,
        'total_page': total_page
    }
    return render_template('admin/news_review.html', data = data)

@admin_blu.route('/news_review_action', methods=['POST'])
@admin_blu.route('/news_review_action/<int:news_id>',methods=['GET'])
def news_review_detail(news_id = None):

    if request.method == 'POST':
        #取得前端审核结果参数
        params = request.get_json()
        action = params.get('action')
        reason = params.get('reason')
        id = params.get('news_id')
        # 查询审核细节的新闻信息
        news = News.query.filter(News.id == id).first()
        if action == 'accept':
            #审核结果通过
            news.status = 0
        elif action == 'reject':
            #审核结果为不通过
            news.status = -1
            news.reason = reason
        else:
            return jsonify(errno = RET.PARAMERR, errmsg = '参数有误')

        #提交审核结果到数据库
        db.session.add(news)
        db.session.commit()
        return jsonify(errno = RET.OK, errmsg = '审核成功')
    else:
        # 查询审核细节的新闻信息
        news = News.query.filter(News.id == news_id).first()
        data = {
            'news': news
        }
        return render_template('admin/news_review_detail.html', data = data)


@admin_blu.route('/news_edit/')
def news_edit():
    # 获取前端的搜索关键字
    keywords = request.args.get('keywords')
    # 接收前端传来的页数，默认1
    current_page = int(request.args.get('p', 1))
    # 查询新闻的总数
    total_count = News.query.count()
    # 计算新闻的总页数
    total_page = total_count // constants.ADMIN_NEWS_PAGE_MAX_COUNT
    if keywords != None:
        # 按照注册时间排序，并将关键字匹配分页之后的用户数据存入paginate
        paginates = News.query.filter(News.title.like('%' + keywords + '%')).order_by(News.create_time.desc()).paginate(current_page, constants.ADMIN_NEWS_PAGE_MAX_COUNT)
    else:
        # 按照注册时间排序，并将分页之后的用户数据存入paginate
        paginates = News.query.order_by(News.create_time.desc()).paginate(current_page, constants.ADMIN_NEWS_PAGE_MAX_COUNT)
    # 查询当前页的新闻数据
    news_list = paginates.items

    data = {
        'news_list': news_list,
        'current_page': current_page,
        'total_page': total_page
    }
    return render_template('admin/news_edit.html',data = data)

@admin_blu.route('/news_edit_detail', methods = ['POST'])
@admin_blu.route('/news_edit_detail/<int:news_id>', methods = ['GET'])
def news_edit_detail(news_id = None):
    if request.method == 'POST':
        #获取前端提交的表单数据
        title = request.form.get('title')
        category_id = request.form.get('category_id')
        digest = request.form.get('digest')
        index_image = request.files.get('index_image')
        content = request.form.get('content')
        id = request.form.get('news_id')
        if not all([title, category_id, digest, content, id]):
            return jsonify(errno = RET.PARAMERR, errmsg = '参数不全')
        else:
            #查询需要编辑的新闻
            news = News.query.filter(News.id == id).first()
                #修改编辑后的内容
            news.title = title
            news.category_id = category_id
            news.digest = digest
            if index_image != None:
                image_filename = constants.QINIU_DOMIN_PREFIX + json.loads((storage(index_image.read()).text_body))['key']
                news.index_image_url = image_filename
            news.content = content
                #向数据库提交修改的内容
            db.session.add(news)
            db.session.commit()
            return jsonify(errno = RET.OK, errmsg = '编辑成功')
    # 查询需要编辑的新闻信息
    news = News.query.filter(News.id == news_id).first()
    #查询所有的新闻类型
    categories = Category.query.all()
    data = {
        'news': news,
        'categories': categories
    }
    return render_template('admin/news_edit_detail.html', data = data)

@admin_blu.route('/news_type', methods=['GET','POST'])
def news_type():
    #修改和添加新闻类型
    if request.method == 'POST':
        #获取前端的数据
        params = request.get_json()
        id = params.get('id')
        name = params.get('name')
        if not name != None:
            return jsonify(errno = RET.PARAMERR, errmsg = '参数有误')
        elif id != None:#修改新闻类型
            category = Category.query.filter(Category.id == id).first()
            category.name = name
            db.session.commit()
            return jsonify(errno = RET.OK, errmsg = '修改成功')
        else:#添加新闻类型
            category = Category(name = name)
            db.session.add(category)
            db.session.commit()
            return jsonify(errno = RET.OK, errmsg = '添加成功')
    #查询所有的新闻类型
    categories = Category.query.all()
    data = {
        'categories': categories
    }
    return render_template('admin/news_type.html',data = data)